import re

import requests

import json

import subprocess

import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

from bs4 import BeautifulSoup






packageName = "陈翔六点半"


def getUrl(url):

    print('地址解析中')

    bvideoHTML = requests.get(url)

    values = bvideoHTML.text

    text = BeautifulSoup(values, features='lxml')
    upload_date = re.search('<meta data-vue-meta="true" itemprop="datePublished" content="(\d{4}-\d{2}-\d{2} \d{2}:\d\d:\d\d)">',values).group(1)

    title = text.find('title').contents[0].replace(' ',',').replace('/',',')

    items = text.find_all('script')[2]

    items = items.contents[0].replace('window.__playinfo__=', '')

    obj = json.loads(items)

    videoUrl = obj["data"]["dash"]["video"][0]["baseUrl"]

    audioUrl = obj["data"]["dash"]["audio"][0]["baseUrl"]


    print('地址解析完成')

    return (videoUrl, audioUrl, title,upload_date.replace(" ","_"))





def getvideoAndAudio(url):

    print('开始发送请求')

    #https://www.bilibili.com/video/BV1cU4y1m7c9?spm_id_from=333.1007.extension.content.click

    Url = getUrl(url)

    videoUrl = Url[0]

    audioUrl = Url[1]

    title = Url[2]
    upload_date = Url[3]
    if not os.path.exists(f'./{packageName}'):
        os.mkdir(f'./{packageName}')

    headers = {



        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36',

        # 'Range': 'bytes=0-29609553',

        'Referer': url

    }

    print('请求成功返回')

    print('开始下载视频，音频文件')

    print(f'./{packageName}/video.mp4')

    with open(f'./{packageName}/video.mp4', 'wb') as video:

        video.write(requests.get(videoUrl, headers=headers).content)

    with open(f'./{packageName}/audio.mp3', 'wb') as audio:

        audio.write(requests.get(audioUrl, headers=headers).content)

    

    print('下载完毕')

    return (f'./{packageName}/video.mp4',f'./{packageName}/audio.mp3',title,upload_date)



def video_add_mp4(url):

    print('开始合出音频视频')

    file = getvideoAndAudio(url)

    mp4_file = file[0]

    mp3_file = file[1]

    title = file[3]+"_"+file[2]
    title = title.replace(":","：")

    print(title)

    cmd = f'ffmpeg -i {mp4_file} -i {mp3_file} -acodec copy -vcodec copy ./{packageName}/{title}.mp4'

    subprocess.call(cmd,shell=True)

    print('合成完毕')

    os.remove(mp4_file)

    os.remove(mp3_file)

    print('正在删除临时文件')


option = Options()
option.add_argument("--disable-gpu")
service = Service(r"chromedriver.exe")
driver = webdriver.Chrome(options=option, service=service)
for i in range(30):
    url1 = f"https://space.bilibili.com/19286458/video?tid=0&page={i + 6}&keyword=&order=pubdate"
    print(url1)
    driver.get(url1)
    ul = driver.find_element(By.CLASS_NAME, "cube-list")
    for li in ul.find_elements(By.TAG_NAME, "li"):
        url = li.find_element(By.TAG_NAME, "a").get_attribute("href")
        video_add_mp4(url)


    






